package com.shanyue.redwine.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.shanyue.redwine.R;
import com.shanyue.redwine.databinding.FragmentWinecabinetRecordListBinding;
import com.shanyue.redwine.entity.Page;
import com.shanyue.redwine.entity.WineCabinetRecord;
import com.shanyue.redwine.http.ApiCallBack;
import com.shanyue.redwine.http.ApiResponse;
import com.shanyue.redwine.http.SendBase;
import com.shanyue.redwine.http.rx.RxBus;
import com.shanyue.redwine.utils.Constants;
import com.shanyue.redwine.utils.RecyclerView.BaseViewHolder;
import com.shanyue.redwine.utils.RecyclerView.CommonLoadMoreAdapter;
import com.shanyue.redwine.utils.recycleviewdivider.HorizontalDividerItemDecoration;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;

import java.util.List;

/**
 * @ 创建 huangxiaoyu
 * @创建时间 2018/8/27 8:29
 * @描述 酒柜商品详情
 */
public class FragmentWineCabinetRecordList extends FragmentBase<FragmentWinecabinetRecordListBinding> {
    Subscription refreshDataSubscription;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPage = new Page();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_winecabinet_record_list;
    }

    @Override
    protected String getTitle() {
        return null;
    }

    @Override
    protected void initView(Bundle saveInstanceState) {
        refreshDataSubscription = RxBus.getDefault().toObservable(RxBus.RX_BUS_REFRESH_WINECABINET_LOG, Boolean
                .class).subscribe(aBoolean -> {
            if (aBoolean) {
                mPage.setRefreshAble(true);
                mPage.setPageIndex(1);
                loadData();
            }
        });
        mBinding.srlRefresh.setOnRefreshListener(() -> {
            mPage.setRefreshAble(true);
            mPage.setPageIndex(1);
            loadData();
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager
                .VERTICAL, false);
        mBinding.rvList.setLayoutManager(linearLayoutManager);
        mBinding.rvList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).sizeResId(R
                .dimen.dp10).colorResId(R.color.base_bg).build());
        mBinding.rvList.setAdapter(new CommonLoadMoreAdapter<WineCabinetRecord>(getActivity(), R.layout
                .item_winecabinet_record_list) {


            @Override
            protected void convert(BaseViewHolder holder, WineCabinetRecord item, int position) {
                holder.setText(R.id.tvMsg, item.getMessage());
                if (item.getType() == 1) {
                    holder.setText(R.id.tvDate, "开门日期: " + item.getCreate_date());
                } else if (item.getType() == 2) {
                    holder.setText(R.id.tvDate, "关门日期: " + item.getCreate_date());
                } else {
                    holder.setText(R.id.tvDate, "操作日期: " + item.getCreate_date());
                }
                holder.setText(R.id.tvNo, "订单编号: " + item.getOrder_id());
                holder.setText(R.id.tvAmount, item.getValue());
                holder.setText(R.id.tvBalance, "账户余额: " + item.getBalance());
                if (TextUtils.isEmpty(item.getOrder_id())) {
                    holder.getView(R.id.tvNo).setVisibility(View.GONE);
                    holder.getView(R.id.tvAmount).setVisibility(View.GONE);
                    holder.getView(R.id.tvBalance).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.tvNo).setVisibility(View.VISIBLE);
                    holder.getView(R.id.tvAmount).setVisibility(View.VISIBLE);
                    holder.getView(R.id.tvBalance).setVisibility(View.VISIBLE);
                }
            }

        });
        mBinding.rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (newState == RecyclerView.SCROLL_STATE_IDLE && manager.findLastVisibleItemPosition() >
                        recyclerView.getAdapter().getItemCount() - 5 && mPage.isRefreshAble()) {
                    mPage.setPageIndex(mPage.getPageIndex() + 1);
                    loadData();
                }
            }
        });
        mBinding.srlRefresh.post(() -> loadData());
    }

    void loadData() {
        JSONObject object = new JSONObject();
        object.put("page", mPage.getPageIndex());
        object.put("rows", mPage.getPageSize());
        SendBase sendBase = new SendBase(getActivity(), object);
        mRestClient.getRectService().getResultString(Constants.URL_WINE_CABINET_RECORD, JSON.toJSONString(sendBase,
                SerializerFeature.WriteSlashAsSpecial)).enqueue(new ApiCallBack<String>(getActivity()) {
            @Override
            protected void onResponse(ApiResponse<String> response) {
                String result = response.result;
                result.replace("\\", "");
                List<WineCabinetRecord> orderList = JSON.parseArray(result, WineCabinetRecord.class);
                if (orderList.size() < mPage.getPageSize()) {//灭有数据 不在加载更多
                    mPage.setRefreshAble(false);
                }
                if (mPage.getPageIndex() > 1) {
                    ((CommonLoadMoreAdapter) mBinding.rvList.getAdapter()).append(orderList);
                } else {
                    // TODO: 2018/8/29 提示空数据
                    ((CommonLoadMoreAdapter) mBinding.rvList.getAdapter()).refresh(orderList);
                }
                mBinding.srlRefresh.setRefreshing(false);
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        refreshDataSubscription.unsubscribe();
    }

    public static FragmentWineCabinetRecordList newInstance() {
        FragmentWineCabinetRecordList fragment = new FragmentWineCabinetRecordList();
        return fragment;
    }
}
